// 登录、注册、忘记密码页面板块
import { login } from "../../api/loginApi.js";
import { register } from "../../api/loginApi.js";
import Cookies from 'js-cookie';

const state = {
    token: Cookies.get('token')===undefined?'':Cookies.get('token'), // 登录之后获取的token
    student_id: Cookies.get('student_id')===undefined?'':Cookies.get('student_id'), // 存储学生的id
}

const mutations = { // mutations改变state中的数据
    SET_TOKEN: (state, token) => { // 存储token
        state.token = token;
        Cookies.set('token', token);
    },
    SET_STUDENT_ID: (state, student_id) => { // 存储学生id
        state.student_id = student_id
        Cookies.set('student_id', student_id);
    },
    NULL:()=>{}
}

const actions = { // 发送请求
    // 调用登录接口
    // login({ commit, state }, loginInfo) { // commit 是调用上面mutations中函数的，state是上面的state
    login({ commit}, loginInfo) { // commit 是调用上面mutations中函数的，state是上面的state
        const {account, password} = loginInfo
        return new Promise((resolve, reject) => {
            login({account: account.trim(), password: password}).then(res => {
                if (res.code === 1) { // 登录成功
                    commit('SET_TOKEN', res.data.token)
                    commit('SET_STUDENT_ID', res.data.studentID)
                }
                resolve(res);
            }).catch(error => {
                reject(error)
            })
        })
    },

    register({ commit},info){
        commit('NULL');
        return new Promise((resolve, reject) => {
            register(info).then(res => {
                resolve(res);
            }).catch(error => {
                reject(error)
            })
        })
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}
